#!/usr/bin/env node
import {
	readFile,
	rm,
	stat,
} from 'node:fs/promises';
import {
	exec,
} from 'node:child_process';
import {
	select,
} from '@inquirer/prompts';
import ora from 'ora';
import chalk from 'chalk';
import {
	Command,
} from 'commander';


//region 获取 package.json 信息
const {
	version,
}=JSON.parse(
	await readFile(
		new URL('./package.json',import.meta.url),
		'utf8',
	)
);
//endregion

const program=new Command();
program
	.name('powerful')
	.description('powerful-cli命令行工具, 创建基于webpack的项目')
	.version(version);

//region create命令
program
	.command('create')
	.description('创建项目')
	.argument('<projectName>', '项目名称')
	.action(async (projectName,options) => {
		const stats=await stat(projectName).catch(() => null);
		if(stats){
			console.log(chalk.red(`已经有同名[${stats.isFile()?'文件':'文件夹'}]了!`));
			return;
		}
		const vueVersion=await select({
			message:'请选择vue版本:',
			choices:[
				{
					value:'vue2',
				},
				{
					value:'vue3',
				},
			],
		});
		const spinner=ora('克隆项目').start();
		exec(`git clone --branch ${vueVersion} --depth 1 https://gitee.com/tangguoxiong/powerful-template.git ${projectName}`, (error, stdout, stderr) => {
			if(error){
				spinner.fail(`克隆项目出错: ${chalk.red(stderr)}`);
			}else{
				rm(`${projectName}/.git`, {force:true, recursive:true});
				spinner.succeed();
				console.log(chalk.green('创建成功!'));
			}
		});
	});
//endregion

program.parse();